import React from 'react';
import {Form, Input, Button, message} from 'antd';
import {UserOutlined, LockOutlined} from '@ant-design/icons';
import loginFn from "../../api/user";
import {connect} from "react-redux";

const index = (props) => {
  const onFinish = (values) => {
    console.log( 'Received values of form: ', values );
    props.loginAction( values )
  };

  return (
      <div id="components-form-demo-normal-login">
        <Form
            name="normal_login"
            className="login-form"
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
        >
          <Form.Item
              name="adminname"
              rules={[
                {
                  required: true,
                  message: '请输入管理员账户!',
                },
              ]}
          >
            <Input prefix={<UserOutlined className="site-form-item-icon"/>} placeholder="管理员账户"/>
          </Form.Item>
          <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入正确的密码!',
                },
              ]}
          >
            <Input
                prefix={<LockOutlined className="site-form-item-icon"/>}
                type="password"
                placeholder="密码"
            />
          </Form.Item>


          <Form.Item>
            <Button type="primary" htmlType="submit" className="login-form-button">
              登 录
            </Button>

          </Form.Item>
        </Form>
      </div>
  );
};

export default connect(
    () => ({}),
    (dispatch) => {
      return {
        loginAction(params) {
          loginFn( params ).then( res => {
            const {code} = res
            if (code === '10003') {
              message.error( '密码错误' ).then( r => {
              } )
            } else if (code === '10005') {
              message.error( '用户不存在' ).then( r => {
              } )
            } else {
              message.success( '登陆成功' ).then( r => {
              } )
              console.log( res )
              // 保存状态到本地
              localStorage.setItem( 'token', res.data.token )
              localStorage.setItem( 'adminname', res.data.adminname )
              localStorage.setItem( 'role', res.data.role )
              localStorage.setItem( 'isLogin', true )
              // 更新状态管理器
              dispatch( {type: 'CHANGE_ADMIN_NAME', payload: res.data.adminname} )
              dispatch( {type: 'CHANGE_TOKEN', payload: res.data.token} )
              dispatch( {type: 'CHANGE_ROLE', payload: res.data.role} )
              dispatch( {type: 'CHANGE_LOGIN_STATE', payload: 'true'} )
              window.location.href = '/'
            }
          } )
        }
      }
    }
)( index )
